<template>
  <div>
    <PerfectTableComponent
      :loadTableList="loadTableList"
      :changePageSize="changePageSize"
      :changePage="changePage"
      :removeQueryField="removeQueryField"
      :clearQuery="clearQuery"
      v-model:query="query"
      title="日志"
      ref="tableRef"
      :queryFormHeaders="queryFormHeaders"
      :table="table"
      :tableColumns="tableColumns"
      :operatorColumnWidth="250"
      :baseUrl="urls.API_URL_BACKSTAGE_DAILYT_MANAGE"
      dialogWidth="1000"
      :formHeader="formHeader"
      v-model:form="form"
      @beforeAddRow="beforeAddRow"
      @afterLoadDataSuccessInEditRow="afterLoadDataSuccessInEditRow"
      @beforeFormSubmit="beforeFormSubmit"
    >
      <!-----------------------------表格自定义列----------------------------------------->
      <!--账户姓名-->
      <template #table_column_authorName="scope: any">
        {{ scope.row.author != null ? scope.row.author.nickName : '' }}
      </template>
      <!--所属栏目-->
      <template #table_column_dailyTypeName="scope: any">
        {{ scope.row.dailyType != null ? scope.row.dailyType.name : '' }}
      </template>
      <!--标题图片-->
      <template #table_column_fileResourceUrl="scope: any">
        <PictureComponent :picUrl="scope.row.fileResource != null ? scope.row.fileResource.fileHttpUrl : ''" :noPicUrl="noPhotoSrc" />
      </template>

      <!-----------------------------表格自定义列（操作列）----------------------------------------->
      <template #table_operator_left="scope">
        <el-button
          @click="
            router.push({
              path: '/backstage/system/daily/preview',
              query: {
                dailyId: scope.row.id
              }
            })
          "
          type="primary"
          size="small"
          icon="User"
          plain
          >预览</el-button
        >
      </template>
      <!-----------------------------表单自定义元素----------------------------------------->
      <!-- <template #dialog_form_fileResourceId>
        <PhotoSelectInput v-model="form['fileResourceId']" />
      </template> -->
      <!-----------------------------表单自定义元素----------------------------------------->
    </PerfectTableComponent>
  </div>
</template>

<script setup lang="ts">
import PerfectTableComponent from '@/components/base/table/PerfectTableComponent.vue';
import PictureComponent from '@/components/base/other/PictureComponent.vue';
import useTableList from '@/api/hooks/useTableList';
import urls from '@/api/request/urls';
import { onMounted, provide, ref, onBeforeUnmount, shallowRef, nextTick } from 'vue';
import type { FormHeader, TableColumn } from '@/types/interface/base_interface';
import { getDict, yesOrNoDict } from '@/api/dict';
import type { Daily, DailyType } from '@/types/interface/sys_interface';
import Request from '@/api/request/request';
import { useRouter } from 'vue-router';
import { noPhotoSrc } from '@/api/pic';
// 表格工具必备参数
const { table, query, loadTableList, removeQueryField, clearQuery, changePageSize, changePage } = useTableList(urls.API_URL_BACKSTAGE_DAILYT_MANAGE);
// 将表格刷新函数传到子容器
provide('loadTableList', loadTableList);
// 导入路由
const router = useRouter(); // 创建路由对象
//查询==========================================================
const queryFormHeaders = ref<FormHeader[]>([]);

const getDailyType = async () => {
  const resData: any = await new Request(urls.API_URL_BACKSTAGE_DAILYTYPE_MANAGE + '/all').get();
  if (resData.success) {
    return resData.data;
  }
};
//表格==========================================================
// 表格插件ref对象
const tableRef = ref();

//表格列
// 定义表格所有的列字段信息
const tableColumns = ref<TableColumn[]>([
  {
    label: '标题',
    prop: 'title',
    fixed: true,
    width: 300,
    align: 'left'
  },
  {
    label: '标题图片',
    prop: 'fileResourceUrl',
    type: 'custom',
    width: 100
  },
  {
    label: '所属栏目',
    prop: 'dailyTypeName',
    type: 'custom',
    width: 100
  },
  {
    label: '排序',
    prop: 'sort'
  },
  {
    label: '前台显示',
    prop: 'display',
    width: 100,
    type: 'dict',
    dict: yesOrNoDict
  },
  {
    label: '作者',
    prop: 'authorName',
    type: 'custom'
  },
  {
    label: '创建时间',
    prop: 'createTime',
    width: 180
  },
  {
    label: '最后编辑时间',
    prop: 'updateTime',
    width: 180
  }
]);
//表单==========================================================
//表单对象
const form = ref<Daily>({});
//表单元素类型
const formHeader = ref<FormHeader[]>([]);
onMounted(async () => {
  //获取日志类别列表
  const dailyTypes = await getDailyType();
  //定义优先级选项。放在mounted中执行时，要将引用改变量的属性也放进来。
  const sortDict = await getDict('优先级', 'number');
  queryFormHeaders.value = [
    // 查询表单
    {
      prop: 'title',
      label: '标题'
    },
    {
      prop: 'dailyTypeId',
      propAsName: 'dailyType.id',
      label: '日志类型',
      type: 'selectObject',
      list: dailyTypes,
      config: {
        valueKey: 'id',
        defaultProp: {
          value: 'id',
          label: 'name'
        }
      }
    },
    {
      prop: 'display',
      label: '前台显示',
      type: 'select',
      list: yesOrNoDict
    }
  ];
  //表单组成
  formHeader.value = [
    // 查询表单
    {
      prop: 'fileResourceId',
      label: '标题图片',
      type: 'photoSelect',
      rules: [
        {
          required: true,
          message: '不能为空',
          trigger: 'blur'
        }
      ]
    },
    {
      prop: 'dailyTypeId',
      label: '日志类型',
      type: 'selectObject',
      list: dailyTypes,
      config: {
        valueKey: 'id',
        defaultProp: {
          value: 'id',
          label: 'name'
        }
      },
      rules: [
        {
          required: true,
          message: '不能为空',
          trigger: 'blur'
        }
      ]
    },
    {
      label: '标题',
      prop: 'title',
      rules: [
        {
          required: true,
          message: '不能为空',
          trigger: 'blur'
        },
        {
          min: 2,
          max: 50,
          message: '长度在 2 到 50个字符',
          trigger: 'blur'
        }
      ]
    },
    {
      label: '排序',
      prop: 'sort',
      type: 'select',
      list: sortDict,
      rules: [
        {
          required: true,
          message: '不能为空',
          trigger: 'blur'
        }
      ]
    },
    {
      label: '摘要',
      prop: 'expert',
      type: 'textarea',
      rules: [
        {
          required: true,
          message: '不能为空',
          trigger: 'blur'
        }
      ]
    },
    {
      label: '内容',
      prop: 'content',
      type: 'editor',
      rules: [
        {
          required: true,
          message: '不能为空',
          trigger: 'blur'
        }
      ]
    },
    {
      label: '是否前台显示',
      prop: 'display',
      type: 'switch'
    }
  ];
});

//在添加行的动作以前
const beforeAddRow = async () => {
  //传入初始值
  form.value = {
    sort: 100,
    display: true,
    content: ''
  };
};
//在编辑行读取后端记录后需要修改的地方
const afterLoadDataSuccessInEditRow = async (formEdit: Daily) => {
  //重新封装表单对象的值
  if (formEdit.dailyType != null) {
    formEdit.dailyTypeId = formEdit.dailyType.id;
  }
  if (formEdit.fileResource != null) {
    formEdit.fileResourceId = formEdit.fileResource.id;
  }
};
//在表单提交前对对象进行封装
const beforeFormSubmit = () => {
  if (form.value.dailyTypeId != null) {
    form.value.dailyType = {
      id: form.value.dailyTypeId
    };
  }
  if (form.value.fileResourceId != null && form.value.fileResourceId.length > 0) {
    form.value.fileResource = {
      id: form.value.fileResourceId
    };
  }
};
</script>

<style scoped></style>
